<?php
/**
 * 装修公司评价
 */
namespace Beerus\Modules\DecoCompany\Controllers;

use App\Http\Controllers\Controller;
use Beerus\Modules\DecoCompany\Actions\CancelFold;
use Beerus\Modules\DecoCompany\Actions\delEvaluation;
use Beerus\Modules\DecoCompany\Actions\FoldEvaluation;
use Beerus\Modules\DecoCompany\Actions\RecoverEvaluate;
use Doraemon\cache\Queue;
use Doraemon\cache\UserCounter;
use Doraemon\model\BindDesignerArticle;
use Doraemon\model\DecoCompany;
use Doraemon\model\DecoCompanyEvaluation;
use Doraemon\model\Member;
use Doraemon\service\DecoCompanyEvaluationService;
use Doraemon\service\position\PositionApi;
use Doraemon\service\User;
use Doraemon\service\Designer\DesignerEvaluation as sDesignerEvaluation;
use Doraemon\service\UserPortrait\UserPortraitApi;
use Doraemon\tools\HhzNiceLivingUrl;
use Doraemon\tools\ImgUrl;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Grid;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Doraemon\service\Sysmsg;
use Illuminate\Support\MessageBag;

class EvaluationController extends Controller
{
    const DEFAULT_HAOHAOZHU_UID = 11941;
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content)
    {
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);

        $condition = [
            'type' => DecoCompanyEvaluation::TYPE_USER_EVALUATION,
        ];
        if (!empty($request['to_user'])) {
            if (is_numeric($request['to_user'])) {
                $to_uid = $request['to_user'];
            } else {
                $to_uid = Member::get('uid', ['nick' => $request['to_user']]);
            }
            $condition['to_uid'] = $to_uid;
        }
        if (!empty($request['from_user'])) {
            if (is_numeric($request['from_user'])) {
                $from_uid = $request['from_user'];
            } else {
                $from_uid = Member::get('uid', ['nick' => $request['from_user']]);
            }
            $condition['from_uid'] = $from_uid;
        }
        if (!empty($request['id'])) {
            $condition['id'] = $request['id'];
        }
        if (!empty($request['audit_status'])) {
            $condition['audit_status'] = $request['audit_status'];
        }
        if (!empty($request['reality'])) {
            $condition['reality'] = $request['reality'];
        }
        if (!empty($request['quality'])) {
            $condition['quality'] = $request['quality'];
        }
        if (!empty($request['created_at']['start'])) {
            $condition['created_at[>=]'] = strtotime($request['created_at']['start']. ' 00:00:00');
        }
        if (!empty($request['created_at']['end'])) {
            $condition['created_at[<=]'] = strtotime($request['created_at']['end']. ' 23:59:59');
        }
        $total = DecoCompanyEvaluation::count($condition);
        $condition['ORDER'] = ['created_at' => 'DESC'];
        $condition['LIMIT'] = [
            ($page - 1) * $page_size,
            $page_size
        ];
        $lists = DecoCompanyEvaluation::select('*', $condition) ?: [];
        self::formatList($lists);

        $gridModel = new pGridDataModel($lists, $total, [
            'perPage' => $page_size
        ]);
        $search_params = http_build_query($condition);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel, $search_params) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableCreateButton();

                //$grid->disableActions();
                $grid->setActionClass(DropdownActions::class);

                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();

                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('from_user', '评价人uid/昵称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('to_user', '被评价人uid/昵称');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->between('created_at', '评价时间')->date('Y-m-d');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('audit_status', '审核状态')->select(DecoCompanyEvaluation::CHECK_STATUS_TEXT);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('reality', '内容真实性')->select(DecoCompanyEvaluation::REALITY_TEXT);
                    });
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('quality', '内容质量')->select(DecoCompanyEvaluation::COMMENT_TEXT);
                    });

                    $filter->expand();
                });

                $grid->column('id', 'id')->display(function () {
                    return '<a href="/admin/DecoCompany/evaluation/' . $this->id . '/edit">' .$this->id . '</a>';
                });
                $grid->column('from_uid', '用户UID');
                $grid->column('from_nick', '用户昵称')->display(function() {
                    return '<a href="https://frieza.haohaozhu.me/admin/user/Detail/' . $this->from_uid . '" target="_blank">' . $this->from_nick . '</a>';
                })->width(100);
                $grid->column('to_uid', '装修公司UID');
                $grid->column('to_nick', '装修公司昵称')->display(function() {
                    return '<a href="https://frieza.haohaozhu.me/admin/user/Detail/' . $this->to_uid . '" target="_blank">' . $this->to_nick . '</a>';
                })->width(100);
                $grid->column('content', '评价内容')->width(200);
                $grid->column('images', '评价图片')->width(180)->display(function() {
                    $img = '';
                    if ($this->images) {
                        foreach ($this->images as $imageUrl) {
                            $img .= "<a href='{$imageUrl['pic_url']}' target='_blank'><img width='80' height='80' style='margin-bottom: 10px;padding-right: 10px;' src='{$imageUrl['thumb_pic_url']}'></a>";
                        }
                    }
                    return $img;
                });
                $grid->column('proof', '合同截图')->display(function() {
                    $img = '';
                    if ($this->proof) {
                        foreach ($this->proof as $imageUrl) {
                            $img .= "<a href='{$imageUrl['pic_url']}' target='_blank'><img width='80' height='80' src='{$imageUrl['thumb_pic_url']}'></a><br><br>";
                        }
                    }
                    return $img;
                });
//                $grid->column('score', '评价各项得分')->display(function() {
//                    return "设计方案：{$this->design_score}<br>
//                                服务态度：{$this->service_score}<br>
//                                沟通能力：{$this->communication_score}<br>
//                                施工能力：{$this->construction_score}";
//                });
                $grid->column('overall_type', '总评价')->display(function() {
                    return DecoCompanyEvaluation::RECOMMEND_TEXT[$this->overall_type];
                });
                $grid->column('created_date', '评价时间')->width(100);
                $grid->column('article_id', '关联整屋案例')->width(100);
                $grid->column('audit_status', '审核状态')->display(function() {
                    return DecoCompanyEvaluation::CHECK_STATUS_TEXT[$this->audit_status];
                });
                $grid->column('quality', '内容质量')->display(function() {
                    return in_array($this->audit_status, [DecoCompanyEvaluation::STATUS_CHECK_PASS, DecoCompanyEvaluation::STATUS_CHECK_REVIEW]) ? DecoCompanyEvaluation::COMMENT_TEXT[$this->quality] : '';
                });
                $grid->column('reality', '是否真实')->display(function() {
                    return in_array($this->audit_status, [DecoCompanyEvaluation::STATUS_CHECK_PASS, DecoCompanyEvaluation::STATUS_CHECK_REVIEW]) ? DecoCompanyEvaluation::REALITY_TEXT[$this->reality] : '';
                });
                $grid->column('data_status', '状态')->display(function() {
                    return DecoCompanyEvaluation::DATA_STATUS_TXT[$this->data_status];
                });

                $grid->column('is_fold', '折叠状态')->display(function() {
                    return DecoCompanyEvaluation::FOLD_TXT[$this->is_fold];
                });
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    $actions->disableView();
                    $actions->disableDelete();
                    if ($actions->row->data_status == DecoCompanyEvaluation::STATUS_DELETE) {
                        $actions->disableEdit();
                        $actions->add(new RecoverEvaluate());
                    }
                    if ($actions->row->data_status == DecoCompanyEvaluation::STATUS_NORMAL){
                        $actions->add(new delEvaluation());
                    }
                    if ($actions->row->is_fold == DecoCompanyEvaluation::FOLD_NORMAL && in_array($actions->row->audit_status, [DecoCompanyEvaluation::STATUS_CHECK_PASS, DecoCompanyEvaluation::STATUS_CHECK_REVIEW])){
                        $actions->add(new FoldEvaluation());
                    }
                    if($actions->row->is_fold == DecoCompanyEvaluation::FOLD_HIDDEN){
                        $actions->add(new CancelFold());
                    }

                });
            }
        );

        $tab = new Tab();
        $tab->add('装企评价管理', $gridList->render());
        $content->row($tab);
        return $content
            ->header('装企评价管理')
            ->description(' ')
            ->breadcrumb(['text' => '装企评价管理']);
    }

    // 删除奖项
    public function del($id) {
        $update_data = [
            'data_status' => DecoCompanyEvaluation::STATUS_DELETE,
            'admin_id' => Admin::user()->id,
        ];
        if (is_numeric($id)) {
            // 单个删除
            if (!DecoCompanyEvaluation::update($update_data, ['id' => $id])) {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        } else {
            // 批量删除
            $id = explode(',', $id);
            if (!DecoCompanyEvaluation::update($update_data, ['id' => $id])) {
                return response()->json([
                    'status' => false,
                    'message' => "操作失败",
                ]);
            }
        }
        $sysMsgParams = [
            'msgCode' => 0,
            'msgParams' => [
                'from_uid'=> self::DEFAULT_HAOHAOZHU_UID,
                'title' => '',
                'detail' => delEvaluation::MSG_DETAIL,
            ],
        ];
        $evaluation_info = DecoCompanyEvaluation::select(['from_uid', 'to_uid'], ['id' => $id]);
        foreach ($evaluation_info as $item) {
            $sysMsgParams['to_uid'] = $item['from_uid'];
            Sysmsg::sendSingleMsg($sysMsgParams);
            if ($item['type'] == DecoCompanyEvaluation::TYPE_USER_EVALUATION) {
                DecoCompanyEvaluationService::reCalculateScore($item['to_uid']);
                // 同步评价好评率
                Queue::insertQueue('/queue/Decocompany/AsyncFavorRating',[
                    'uid' => $item['to_uid'],
                ], Queue::QUEUE_DORAEMON);
            }
        }
        return response()->json([
            'status' => true,
            'message' => "操作成功",
        ]);
    }

    public static function formatList(&$list) {
        $all_from_uid = array_column($list, 'from_uid');
        $all_to_uid = array_column($list, 'to_uid');
        $all_uid = array_merge($all_from_uid, $all_to_uid);
        $all_uid = array_values(array_unique($all_uid));
        if (empty($all_uid)) {
            return [];
        }
        // 查询这一批评论用户及装修公司的用户信息
        $member_info = Member::select(['uid', 'nick'], ['uid' => $all_uid]);
        $member_map = array_column($member_info, 'nick', 'uid');

        foreach ($list as &$item) {
            $item['from_nick'] = $member_map[$item['from_uid']] ?: '';
            $item['to_nick'] = $member_map[$item['to_uid']] ?: '';
            $item['images'] = self::getUrl($item['images']);
            $item['proof'] = self::getUrl($item['proof']);
            $item['created_date'] = date('Y-m-d H:i:s', $item['created_at']);
            $flag_uid_designer[] = $item['from_uid']. '-' .$item['to_uid'];
        }
        unset($item);

        // 先查询与这一批装修公司绑定的整屋案例信息
        $map_uid_house_case = BindDesignerArticle::select(['aid', 'uid', 'bind_uid'], [
            'status' => BindDesignerArticle::STATUS_NORMAL,
            'bind_uid' => $all_to_uid
        ]);
        $map_uid_house_case = is_array($map_uid_house_case) ? $map_uid_house_case : [];

        // 确定每条评价记录是否有绑定整屋案例信息
        $map_row_house = [];
        foreach ($map_uid_house_case as $item) {
            $flag = $item['uid']. '-' .$item['bind_uid'];

            if (in_array($flag, $flag_uid_designer)) {
                // 记录每条绑定有整屋案例的评价的整屋案例id
                $map_row_house[$flag] = $item['aid'];
            }
        }
        foreach ($list as &$item) {
            $item['article_id'] = empty($map_row_house[$item['from_uid']. '-' .$item['to_uid']]) ? '' : $map_row_house[$item['from_uid']. '-' .$item['to_uid']];
        }
        unset($item);
    }

    public static function getUrl($images)
    {
        $data = [];
        if (!empty($images)) {
            $result = json_decode($images, true);
            $result = empty($result) ? [] : $result;

            foreach ($result as $item) {
                $data[] = [
                    'pic_id' => $item['pic_id'],
                    'pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $item['pic_id'], ImgUrl::IMAGE_SIZE_SQ_PHONE),
                    'thumb_pic_url' => ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $item['pic_id'], ImgUrl::IMAGE_SIZE_SQ_THUMB)
                ];
            }
        }

        return $data;
    }

    // 编辑
    public function edit(Content $content, $id)
    {
        $data = DecoCompanyEvaluation::getById($id);
        $proof_arr = json_decode($data['proof'], true);
        $data['proof'] = !empty($proof_arr) ? implode(',', array_column($proof_arr, 'pic_id')) : '';

        $images_arr = json_decode($data['images'], true);
        $data['images'] = !empty($images_arr) ? implode(',', array_column($images_arr, 'pic_id')) : '';
        $data['sign_status_text'] = DecoCompanyEvaluation::SIGN_TEXT[$data['sign_status']];
        $data['is_advisory_text'] = DecoCompanyEvaluation::ADVIDORY_TEXT[$data['is_advisory']];

        //用户基本信息
        $user_basic_info = User::getBasicUserInfoByCacheWithAvatar($data['from_uid']);
        $data['nick'] = $user_basic_info['nick'];//昵称
        $data['avatar'] = $user_basic_info['avatar'];//头像
        $data['area_code'] = $user_basic_info['area_code'];//地区
        $data['register_day'] = floor((time() - $user_basic_info["addtime"])/(3600*24));//注册天数

        //装修公司信息
        $deco_company = DecoCompany::getByUid($data['to_uid']);
        $main_area_code = explode(',', $deco_company['main_area_code']);
        $data['same_area'] = in_array($data['area_code'], $main_area_code) ? 1 : 0;

        //计数器
        $counterArr = UserCounter::getOne($data['from_uid']);
        $belieked_num = $counterArr['beliked'];//被点赞数
        $favorited_num = $counterArr['befavorited'];//处理被收藏数
        $data['belieked_favorited_num'] = $belieked_num + $favorited_num;

        //用户画像
        //$es_info = PositionApi::getOneUserProfile($data['from_uid'],['logindays']);
        $es_info = UserPortraitApi::request($data['from_uid'], ['logindays'], UserPortraitApi::DESIGNER_TOKEN);
        $data['login_days'] = $es_info['logindays'] ?: 0;//登录天数,没有测试和开发环境

        //用户生产内容数据
        $user_counter = User::get_counter($data['from_uid']);
        $note_num = $user_counter["photo"];//note数
        $article_num = $user_counter["article"];//整屋案例数
        $blank_num = $user_counter["blank"];//经验文章数
        $diary_num = $user_counter["diary"];//日记数
        $data['content_num'] = $note_num + $article_num + $blank_num + $diary_num;

        // 如果是待复审则置成审核通过，目的是显示审核记录
        if ($data['audit_status'] == DecoCompanyEvaluation::STATUS_CHECK_REVIEW) {
            $data['audit_status'] = strval(DecoCompanyEvaluation::STATUS_CHECK_PASS);
        }

        return $content
            ->header('审核评价')
            ->breadcrumb([
                'text' => '评价列表',
                'url' => '/Designer/evaluation',
            ])
            ->row(function (Row $row) use ($data) {
                $row->column(6, $this->detailForm($data));
                $row->column(6, $this->auditForm($data));
            });
    }

    public function detailForm($data)
    {
        $form = new Form($data);
        $form->disableReset();
        $form->disableSubmit();
        $form->hidden('id');

        //$form->display('nick', '用户头像及昵称')->setWidth(4, 2);
        $form->display('用户头像及昵称')->default("<span style='color: red'>{$data['nick']}</span><img  width='50px;' src='{$data['avatar']}.'/>")->setWidth(7, 2);

        if ($data['register_day'] >= 30) {
            $form->display('注册天数')->default("<span style='color: green'>{$data['register_day']}</span>")->setWidth(7, 2);
        } else {
            $form->display('注册天数')->default("{$data['register_day']}")->setWidth(7, 2);
        }

        if ($data['login_days'] >= 30) {
            $form->display('登录天数')->default("<span style='color: green'>{$data['login_days']}</span>")->setWidth(7, 2);
        } else {
            $form->display('登录天数')->default("{$data['login_days']}")->setWidth(7, 2);
        }

        if ($data['content_num'] > 0) {
            $form->display('创作内容数')->default("<span style='color: green'>{$data['content_num']}</span>")->setWidth(7, 2);
        } else {
            $form->display('创作内容数')->default("{$data['content_num']}")->setWidth(7, 2);
        }

        if ($data['belieked_favorited_num'] >= 20) {
            $form->display('赞与收藏')->default("<span style='color: green'>{$data['belieked_favorited_num']}</span>")->setWidth(7, 2);
        } else {
            $form->display('赞与收藏')->default("{$data['belieked_favorited_num']}")->setWidth(7, 2);
        }

        if ($data['same_area'] == 1) {
            $form->display('与设计师服务城市')->default("<span style='color: green'>符合</span>")->setWidth(7, 2);
        } else {
            $form->display('与设计师服务城市')->default("不符合")->setWidth(7, 2);
        }

        if ($data['is_advisory'] == DecoCompanyEvaluation::HAS_ADVIDORY) {
            $form->display('是否咨询过')->default("<span style='color: green'>{$data['is_advisory_text']}</span>")->setWidth(7, 2);
        } else {
            $form->display('是否咨询过')->default("{$data['is_advisory_text']}")->setWidth(7, 2);
        }

        $form->display('sign_status_text', '评价类型')->setWidth(7, 2);
        $form->imgUpload('proof', '合同截图', true, [
            'isUpload' => false,
            'imgType' => ImgUrl::APPTYPE_APP,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->setWidth(7, 2);
        $form->display('content', '评价内容')->setWidth(7, 2);
        $form->imgUpload('images', '评价图片', true, [
            'isUpload' => false,
            'imgType' => ImgUrl::APPTYPE_APP,
            'imgSize' => ImgUrl::IMAGE_SIZE_ORI_PHONE_BIG,
        ])->setWidth(7, 2);
        return $form->render();
    }

    public function auditForm($data)
    {
        Admin::script(<<<SCRIPT
        
		$(document).ready(function(){
		    var isAdvisory = $('input[type=hidden][name=is_advisory]').val();
            if (isAdvisory == 0) {
                // 未咨询设置不真实
                $('.reality[value=1]').attr('checked', 'checked');
                $('.reality[value=1]').parent().addClass('checked');
                $("input:radio[name='reality']:not(:checked)").parent().css("background-color", "rgb(183 183 183)");
                $("input:radio[name='reality']:not(:checked)").parent().css("border-radius", "18px");
                $("input:radio[name='reality']:not(:checked)").attr("disabled", true).prop("disabled", true);
                
                $('.unreality_reason[value=1]').attr('checked', 'checked');
                $('.unreality_reason[value=1]').parent().addClass('checked');
                $('.unreality_reason[value=1]').parent().attr('aria-checked', 'true');
                $('.unreality_reason[value=1]').parent().css("background-color", "rgb(183 183 183)");
                $("input:checkbox[name='unreality_reason[]']").eq(0).attr("disabled", true).prop("disabled", true);
            }
		    
            $(':submit').click(function(e){
                e.preventDefault();
                var auditStatus = $('input[type=radio][name=audit_status]:checked').val();
                if (auditStatus == '' || auditStatus == undefined) {
                    layer.msg('请选择是否通过审核');
                    return false;
                } else if (auditStatus == 2) {
                    // 通过
                    var quality = $('input[type=radio][name=quality]:checked').val();
                    if (quality == '' || quality == undefined) {
                        layer.msg('请选择内容质量');
                        return false;
                    }
                    
                    var reality = $('input[type=radio][name=reality]:checked').val();
                    if (reality == '' || reality == undefined) {
                        layer.msg('请选择是否真实');
                        return false;
                    }
                    
                    if (reality == 1) {
                        var unrealityReasonArr =[]; //定义一个空数组
                        $("input:checkbox[name='unreality_reason[]']:checked").each(function(){   //each为每个匹配元素规定运行的函数，匹配name="ipResolve"的复选框
                            unrealityReasonArr.push($(this).val()); //js push增加数组值
                        });
                        var unrealityReason = unrealityReasonArr.join(',');
                        console.log(unrealityReason);
                    }
                    
                } else if (auditStatus == 4) {
                    // 不通过
                    var unAuditReason = $('input[type=radio][name=unaudit_reason]:checked').val();
                    if (unAuditReason == '' || unAuditReason == undefined) {
                        layer.msg('请选择不审核理由');
                        return false;
                    }
                }
                
                layer.confirm('确定提交审核吗', {
                        btn: ['确定', '取消']
                    }, function (index) {
                        layer.close(index);
                        //var form = $('form');
                        //form.submit();
                        var previous_url = $('input[type=hidden][name=previous_url]').val();
                        var id = $('input[type=hidden][name=id]').val();
                        var url = '/admin/DecoCompany/evaluation/check';
                        var params = {id:id,auditStatus:auditStatus,quality:quality,reality:reality,unAuditReason:unAuditReason,unrealityReason:unrealityReason}
                        $.post(url, params , function (result) {
                            if (result.code == 1) {
                                layer.msg(result.msg);
                                setTimeout(function () {
                                    window.location.href = previous_url;
                                }, 1000);
                            } else {
                                layer.msg(result.msg);
                            }
                        });
                });
            })
		});
SCRIPT);

        $data['previous_url'] = url()->previous();

        $form = new Form($data);
        $unaudit_reason_help = '住友将会收到对应的审核失败理由，评价会仅自己可见，不对外展示';

        $form->hidden('id');
        $form->hidden('is_advisory');
        $form->hidden('previous_url');
        $form->radio('audit_status', '该评价是否通过审核')
            // 审核不通过
            ->when(DecoCompanyEvaluation::STATUS_CHECK_FAIL, function (Form $form) use ($data, $unaudit_reason_help) {
                if ($data['sign_status'] == DecoCompanyEvaluation::HAS_SIGN) {// 已签约
                    $form->radio('unaudit_reason', '不通过理由')->options(DecoCompanyEvaluation::UNAUDIT_REASON_TEXT)
                        ->default($data['unaudit_reason'])->stacked()
                        ->help($unaudit_reason_help)->setWidth(7, 4);
                } elseif ($data['sign_status'] == DecoCompanyEvaluation::NO_SIGN) { //未签约
                    $form->radio('unaudit_reason', '不通过理由')->options([
                        DecoCompanyEvaluation::CONTENT_VIOLATION => '内容违规',
                    ])->default($data['unaudit_reason'])->stacked()
                        ->help($unaudit_reason_help)->setWidth(7, 4);
                }

            })
            // 审核通过
            ->when(DecoCompanyEvaluation::STATUS_CHECK_PASS, function (Form $form) use ($data) {
                if ($data['sign_status'] == DecoCompanyEvaluation::HAS_SIGN) {// 已签约
                    $form->radio('quality', '评价内容质量')->options(DecoCompanyEvaluation::COMMENT_TEXT)
                        ->default($data['quality'])->setWidth(7, 4);
                    $form->radio('reality', '评价是否真实')->options(DecoCompanyEvaluation::REALITY_TEXT)
                        ->when(DecoCompanyEvaluation::NO_REALITY, function (Form $form) use ($data) {
                            $form->checkbox('unreality_reason', '不确定真实原因')->options(DecoCompanyEvaluation::NO_REALITY_TEXT)
                                ->checked(explode(',', $data['unreality_reason']))->stacked()->setWidth(7, 4);
                        })
                        ->default($data['reality'])->help('未咨询时，默认选择「不确定」且不可更改，原因默认选择「未在平台发出咨询」不可取消勾选')->setWidth(7, 4);
                } elseif ($data['sign_status'] == DecoCompanyEvaluation::NO_SIGN) {// 未签约
                    $form->radio('quality', '评价内容质量')->options(DecoCompanyEvaluation::COMMENT_TEXT)
                        ->default($data['quality'])->setWidth(7, 4);
                    $form->radio('reality', '评价是否真实')->options(DecoCompanyEvaluation::REALITY_TEXT)
                        ->when(DecoCompanyEvaluation::NO_REALITY, function (Form $form) use ($data) {
                            $form->checkbox('unreality_reason', '不确定真实原因')->options([
                                DecoCompanyEvaluation::NOT_ADVISORY => '未在平台发出咨询',
                                DecoCompanyEvaluation::NOT_TRUE_ACCOUNT => '账号疑似不真实',
                            ])->checked(explode(',', $data['unreality_reason']))->stacked()->setWidth(7, 4);
                        })
                        ->default($data['reality'])->help('未咨询时，默认选择「不确定」且不可更改，原因默认选择「未在平台发出咨询」不可取消勾选')->setWidth(7, 4);
                }
            })
            ->default($data['audit_status'])
            ->options([
                DecoCompanyEvaluation::STATUS_CHECK_PASS => '是',
                DecoCompanyEvaluation::STATUS_CHECK_FAIL => '否',
            ])
            ->setWidth(7, 4);
        $form->action('/admin/DecoCompany/evaluation/check');
        $form->disableReset();
        return $form->render();
    }

    public static function check(Request $request) {
        try {
            $request = $request->all();
            $id = $request['id'];
            $evaluation = DecoCompanyEvaluation::getById($id);
            if (empty($evaluation)) {
                throw new \Exception('评价不存在');
            }

            $auditStatus = $request['auditStatus'];
            $quality = $request['quality'];
            $reality = $request['reality'];
            $unrealityReason = $request['unrealityReason'] ?: '';
            $unAuditReason = $request['unAuditReason'];

            $updateData = [
                'audit_status' => $auditStatus,
                'admin_id' => Admin::user()->id,
                'admin_name' => Admin::user()->username,
                'is_superior' => DecoCompanyEvaluation::SUPERIOR_NO,
            ];

            // 审核通过
            if ($auditStatus == DecoCompanyEvaluation::STATUS_CHECK_PASS) {
                $updateData['quality'] = $quality;
                $updateData['reality'] = $reality;
                $updateData['unreality_reason'] = $unrealityReason;

                if (in_array($evaluation['overall_type'], [DecoCompanyEvaluation::RECOMMEND_POINT, DecoCompanyEvaluation::COMMONLY_POINT])
                    && $quality == DecoCompanyEvaluation::IS_REALITY && $reality == DecoCompanyEvaluation::COMMENT_QUANLITY_GOOD
                ) {
                    $updateData['is_superior'] = DecoCompanyEvaluation::SUPERIOR_YES;
                }

                /*if (in_array($evaluation['audit_status'], [DecoCompanyEvaluation::STATUS_CHECK_WAIT, DecoCompanyEvaluation::STATUS_CHECK_FAIL])) {
                    $sysMsgParams = [
                        'msgCode' => 0,
                        'to_uid' => $evaluation['to_uid'],
                        'msgParams' => [
                            'from_uid'=> self::DEFAULT_HAOHAOZHU_UID,
                            'title' => '',
                            'detail' => '你收到了一条新的住友评价，立即点击查看，评价能够为你更好地打造网络口碑哦～（如无法点击，请把APP更新为最新版本）',
                            'link' => HhzNiceLivingUrl::getCompanyRatingDetailLink($id, $evaluation['to_uid']),
                        ],
                    ];
                    Sysmsg::sendSingleMsg($sysMsgParams);
                }*/ // 注释评价先发后审 By 李柽
            } elseif ($auditStatus == DecoCompanyEvaluation::STATUS_CHECK_FAIL) {
                // 审核不通过
                $updateData['unaudit_reason'] = $unAuditReason;

                if ($evaluation['audit_status'] != DecoCompanyEvaluation::STATUS_CHECK_FAIL) {
                    // 发通知，系统消息
                    $reasonMsgMap = [
                        DecoCompanyEvaluation::CONTENT_VIOLATION => sDesignerEvaluation::MSG_CODE_CONTENT_VIOLATION,
                        DecoCompanyEvaluation::CONTRACT_LACK => sDesignerEvaluation::MSG_CODE_CONTRACT_LACK,
                    ];
                    $reasonMsg = $reasonMsgMap[$unAuditReason];
                    if (!isset($reasonMsg)) {
                        throw new \Exception('不通过消息类型不存在');
                    }
                    $nick = Member::getNickByUid($evaluation['to_uid']);

                    $sysMsgParams = [
                        'msgCode' => $reasonMsg,
                        'to_uid' => $evaluation['from_uid'],
                        'msgParams' => [
                            'nick' => sprintf("装修公司「%s」", $nick),
                            'link' => HhzNiceLivingUrl::getCompanyRatingCreateLink($evaluation['to_uid'], $evaluation['sign_status'], $id),
                        ],
                    ];
                    Sysmsg::sendSingleMsg($sysMsgParams);
                }
            }

            DecoCompanyEvaluation::update($updateData, ['id' => $id])->rowCount();

            DecoCompanyEvaluationService::reCalculateScore($evaluation['to_uid']);
            // 同步评价好评率
            Queue::insertQueue('/queue/Decocompany/AsyncFavorRating',[
                'uid' => $evaluation['to_uid'],
            ], Queue::QUEUE_DORAEMON);

            return response()->json(['code' => 1, 'msg' => '审核成功']);

        } catch (\Exception $e) {
            return response()->json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }


}
